import { Module } from 'vuex'
import {
	accountLoginRequest,
	updateUserInfoRequest
} from '@/service/login/login.js'
import storage from '@/utils/storage.js'
import { mapGetters } from 'vuex'

const loginModule = {
	namespaced: true,
	state() {
		return {
			token: '',
			userInfo: {}
		}
	},
	getters:{
		getUserInfo: state => {
			return state.userInfo
		}
	},
	mutations: {
		changeToken(state, token) {
			state.token  = token
		},
		changeUserInfo(state, userInfo) {
			state.userInfo = userInfo
		}
	},
	actions: {
		async accountLoginAction({ commit, dispatch }, playload){
			// 实现登录逻辑
			let errMsg = null
			const loginResult = await accountLoginRequest(playload).catch(err => {
				errMsg = err
			})
			if(errMsg != null) {
				return errMsg
			}
			const { id, token } = loginResult.data
			commit('changeToken', token)
			storage.set('token', token)
			uni.redirectTo({
				url: '/pages/pets/index'
			})
			
			this.userInfo = loginResult.data.userInfo
			storage.set('userInfo', this.userInfo)
			// 发送初始化的请求
			dispatch('getInitialDataAction', null, { root: true })
			
			// 请求用户信息
		},
		async updateUserInfo({ commit, dispatch }, playload) {
			const userInfoResult = await updateUserInfoRequest(playload)
			// 更新最新的用户信息
			storage.set('userInfo', userInfoResult.data.userInfo)
			storage.set('token',userInfoResult.data.token)
			commit('changeUserInfo', userInfoResult.data)
		},
		test({ commit, dispatch }, playload) {
		}
	}
}

export default loginModule